package chaoyue.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取nacos上配置的所有服务
 * 注册表是会缓存到本地的，本地注册表获取之后nacos宕机依然可以进行服务调用
 */
@Slf4j
@RestController
@RequestMapping("test")
public class DiscoveryController {
    /**
     * springCloud给我们提供了这个客户端
     * 方便我们在需要显式调用具体某一个服务的时候使用
     */
    @Autowired
    private DiscoveryClient client;

    @GetMapping("discovery")
    public List<String> discovery() {
        // 获取注册中心中所有的服务名称
        List<String> services = client.getServices();
        for (String serviceName : services) {
            // 根据服务名称获取对应的服务实例信息
            List<ServiceInstance> instances = client.getInstances(serviceName);
            for (ServiceInstance instance : instances) {
                Map<String, Object> map = new HashMap<>();
                map.put("serviceName", serviceName);
                map.put("serviceId", instance.getServiceId());
                map.put("serviceHost", instance.getHost());
                map.put("servicePort", instance.getPort());
                map.put("uri", instance.getUri());
                log.info("serviceInfo -> {}", map);
            }
        }
        return services;
    }
}
